package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test1 {
    //leetcode 四树之和
    //https://leetcode.cn/problems/4sum/description/
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        if (n < 4) return ret;
        Arrays.sort(nums);
        if (target < 0 && nums[0] >= 0) return ret;
        for (int i = 0; i < n-3; i++) {
            if (i > 0 && nums[i] == nums[i-1]) continue;
            for (int j = i + 1; j < n-2; j++) {
                if (j > i + 1 && nums[j] == nums[j-1]) continue;
                int left = j + 1, right = n-1;
                long tg = (long)target - nums[i] - nums[j];
                while (left < right) {
                    if (nums[left] + nums[right] == tg) {
                        ret.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
                        left++;
                        right--;
                    }else if (nums[left] + nums[right] < tg) {
                        left++;
                    }else {
                        right--;
                    }
                    while (left > j + 1 && left < right && nums[left] == nums[left-1]) left++;
                    while (right < n-1 && left < right && nums[right] == nums[right+1]) right--;
                }
            }
        }
        return ret;
    }
}
